package cn.itcast.utils;

import cn.itcast.pojo.AliPropertise;
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@Component
public class OSSUtils {
    @Autowired
    private AliPropertise aliPropertise;
    /*@Value("${ali.oss.endpoint}")
    private String endpoint;
    @Value("${ali.oss.bucketName}")
    private String bucketName;
    @Value("${ali.oss.region}")
    private String region;*/
    public  String upload(MultipartFile file) throws com.aliyuncs.exceptions.ClientException {
        /*// Endpoint以华东1（杭州）为例，填写为https://oss-cn-hangzhou.aliyuncs.com，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        String bucketName = "shd123";
        // 填写Bucket所在地域。以华东1（杭州）为例，Region填写为cn-hangzhou。
        String region = "cn-beijing";*/

        // 从环境变量中获取访问凭证。运行本代码示例之前，请先配置环境变量
        EnvironmentVariableCredentialsProvider credentialsProvider =
                CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

        // 创建OSSClient实例。
        // 当OSSClient实例不再使用时，调用shutdown方法以释放资源。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        // 显式声明使用 V4 签名算法
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(aliPropertise.getEndpoint())
                .credentialsProvider(credentialsProvider)
                .region(aliPropertise.getRegion())
                .build();
        try {
            // 1. 创建存储空间（Bucket）
            //ossClient.createBucket(bucketName);
            // 2. 上传文件
            //String objectName = "d:/a.jpg";
            log.warn("注入的配置内容是:{}",aliPropertise);
            String originalFilename = file.getOriginalFilename();
            //file.transferTo(new File(originalFilename, UUID.randomUUID().toString()+"_"+originalFilename));
            ossClient.putObject(aliPropertise.getBucketName(), originalFilename, file.getInputStream());
            System.out.println("2. 文件 " + originalFilename + " 上传成功。");
            //https://junjian12345.oss-cn-beijing.aliyuncs.com/b.jpeg?
            return "https://"+aliPropertise.getBucketName()+"."+aliPropertise.getEndpoint().substring(aliPropertise.getEndpoint().lastIndexOf("/")+1)+"/"+originalFilename;
            /*// 3. 下载文件
            OSSObject ossObject = ossClient.getObject(bucketName, objectName);
            InputStream contentStream = ossObject.getObjectContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(contentStream));
            String line;
            System.out.println("3. 下载的文件内容：");
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            contentStream.close();
            // 4. 列出文件
            System.out.println("4. 列出 Bucket 中的文件：");
            ObjectListing objectListing = ossClient.listObjects(bucketName);
            for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
                System.out.println(" - " + objectSummary.getKey() + " (大小 = " + objectSummary.getSize() + ")");
            }
            // 5. 删除文件
            ossClient.deleteObject(bucketName, objectName);
            System.out.println("5. 文件 " + objectName + " 删除成功。");
            // 6. 删除存储空间（Bucket）
            ossClient.deleteBucket(bucketName);
            System.out.println("6. Bucket " + bucketName + " 删除成功。");*/
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException | IOException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }
    private String randomSubDirectory(String originalFilename) {
        int hash = originalFilename.hashCode();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < 8; i++) {
            int subDir = hash & 15;
            stringBuilder.append(subDir + "/");

            hash >>= 4;
        }
        return stringBuilder.toString();
    }
}
